package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author chengjy
 * @date 2023/4/27
 */
@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;

    @Scheduled(cron = "0 1 * * * ?")
    /**
     * 超时未支付订单--15分钟
     */
    public void timeOutOrder(){
        //1、定义超时参数，将15分钟前状态为未支付的订单找出
        //1.1、 15分钟单位
        LocalDateTime localDateTime = LocalDateTime.now().minusMinutes(-5);
        List<Orders> ordersList = orderMapper.selectTimeOutOrder(Orders.PENDING_PAYMENT, localDateTime);
        //2、根据id批量修改订单状态
        //2.1、得到所有id的集合
        List<Long> ids = ordersList.stream().map(order -> order.getId()).collect(Collectors.toList());
        //2.2、修改状态
        Orders orders = Orders.builder().cancelReason("订单超时，已自动取消").status(Orders.CANCELLED).build();
        orderMapper.updateIds(orders, ids);
    }

    @Scheduled(cron = "0 1 * * * ?")
//    @Scheduled(cron = "0 0 1 * * ?")
    /**
     * 第二天还未收货的订单
     */
    public void outOrderDay(){
        //1、定义超时参数，将15分钟前状态为未支付的订单找出
        //1.1、 15分钟单位
//        LocalDateTime localDateTime = LocalDateTime.now().minusDays(-1);
        LocalDateTime time = LocalDateTime.now().plusMinutes(-60);
        List<Orders> ordersList = orderMapper.selectoutOrderDay(Orders.DELIVERY_IN_PROGRESS, time);
        //2、根据id批量修改订单状态
        //2.1、得到所有id的集合
        List<Long> ids = ordersList.stream().map(order -> order.getId()).collect(Collectors.toList());
        //2.2、修改状态
        Orders orders = Orders.builder().status(Orders.COMPLETED).build();
        orderMapper.updateIds(orders, ids);
    }
}
